import Vue from 'vue'

const isServer = Vue.prototype.$isServer

export const onReady = function (callback: EventListener) {
  if (isServer) return
  window.addEventListener('load', callback)
}

export const on = function (
  el: Node,
  type: string,
  callback: EventListener,
  capture = false
) {
  if (isServer) return
  el.addEventListener(type, callback, capture)
}

export const off = function (el: Node, type: string, callback: EventListener) {
  if (isServer) return
  el.removeEventListener(type, callback)
}

export const once = function (el: Node, type: string, callback: EventListener) {
  if (isServer) return
  const listener = function () {
    if (callback) {
      callback.apply(this, arguments)
    }
    off(el, type, listener)
  }
  on(el, type, listener)
}

/**
 * return the rectangle of html element. the top left right bottom are relative to the top-left of the viewpor.
 *
 * @param el html element
 */
export const boundingClientRect = function (
  el: HTMLElement
): {
  bottom: number
  height: number
  left: number
  right: number
  top: number
  width: number
} {
  const domOrClient = el.getBoundingClientRect()
  return {
    bottom: domOrClient.bottom,
    height: domOrClient.height,
    left: domOrClient.left,
    right: domOrClient.right,
    top: domOrClient.top,
    width: domOrClient.width
  }
}

export const offsetRect = function (el: HTMLElement) {
  const { offsetLeft, offsetTop, offsetWidth, offsetHeight } = el
  return { offsetLeft, offsetTop, offsetWidth, offsetHeight }
}
